package jnpf.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import jnpf.util.TenantProvider;
import jnpf.util.UserProvider;
import jnpf.util.data.DataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 *
 * @author JNPF开发平台组
 * @copyright 引迈信息技术有限公司
 */
@Slf4j
@Configuration
public class SecurityConfiguration implements WebMvcConfigurer {


    @Autowired
    private ConfigValueUtil configValueUtil;

    /**
     * 注册sa-token的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器，自定义验证规则
        // 这里只处理登录缓存清理 具体拦截在网关处理
        registry.addInterceptor(new SaInterceptor((handler) -> {
            SaRouter.match("/**", r->{
                //执行Token续期, 存用户信息至本地缓存后续无需重新获取
                UserProvider.renewTimeout();
            });
            //单体版无网关不需要
            /*if(configValueUtil.getEnableInnerAuth()) {
                SaRouter.match("/actuator/**", "/favicon.ico").stop();
                SaRouter.match("/**").match(r->{
                    //验证请求来源, 网关, Feign
                    String innerToken = SaHolder.getRequest().getHeader(AuthConsts.INNER_TOKEN_KEY);
                    if(!UserProvider.isValidInnerToken(innerToken)){
                        log.error("非法请求: {}, {}", SaHolder.getRequest().getRequestPath(), innerToken);
                        return true;
                    }
                    return false;
                }).back("非法请求, 缺少认证信息");
            }*/
        }) {
            @SuppressWarnings("all")
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                UserProvider.clearLocalUser();
                TenantProvider.clearBaseSystemIfo();
                DataSourceContextHolder.clearDatasourceType();
            }
        }.isAnnotation(configValueUtil.isEnablePreAuth())).addPathPatterns("/**");
    }


}
